package com.kun.peng.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kun.peng.system.domain.Dict;
import com.kun.peng.utils.*;
import com.kun.peng.mybatis.base.IBaseService;
import com.kun.peng.system.mapper.DictMapper;
import com.kun.peng.system.service.DictService;
import com.kun.peng.system.service.dto.DictQueryCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created on 2021/12/14.
 *
 * @author xuebaopeng
 * Description
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl extends IBaseService<DictMapper, Dict> implements DictService {

    private final RedisUtils redisUtils;

    @Override
    public IPage<Dict> queryAll(DictQueryCriteria<Dict> criteria) {
      IPage<Dict> dicts= QueryHelp.pageQuery(criteria,Dict.class,getBaseMapper());
      return dicts;
    }

    @Override
    public void create(Dict resources) {
        getBaseMapper().insert(resources);
    }

    @Override
    public void updateDict(Dict resources) {
        // 清理缓存
        delCaches(resources);
        Dict dict = findById(resources.getId()).orElseGet(Dict::new);
        ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
        dict.setName(resources.getName());
        dict.setDescription(resources.getDescription());
        updateById(dict);
    }

    @Override
    public void delete(Set<Long> ids) {
        // 清理缓存
        List<Dict> dicts = getBaseMapper().selectBatchIds(ids);
        for (Dict dict : dicts) {
            delCaches(dict);
        }
        getBaseMapper().deleteBatchIds(ids);
    }

    @Override
    public Dict findDictById(long id) {
        return findById(id).orElseGet(Dict::new);
    }


    public void delCaches(Dict dict){
        redisUtils.del(CacheKey.DICT_NAME + dict.getName());
    }
}
